/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package csse3004.GD.DA;

import csse3004.GD.PC.PollCreatorService;
import csse3004.GD.Poll;
import csse3004.GD.Question;

import csse3004.GD.WBUser.WBUserService;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.logging.Logger;

/**
 *
 * @author Tom McNair - S41758984
 */
public class PollCreatorDA extends GenericDA implements PollCreatorService {

    private static final Logger m_logger = Logger.getLogger(SysAdminDA.class.getName());

    public ArrayList<Poll> getPolls(int creatorID) {

        m_logger.info("\ngetPolls\n\n");

        String sql = "SELECT Poll.Poll_ID, Poll.Poll_Name, Poll.Public_Result, "
                + "Poll.Anonymous, Poll.Admin_ID, Poll.Creation_Date "
                + "FROM Poll, Poll_Creator WHERE Poll.Poll_ID = Poll_Creator.Poll_ID "
                + "AND Poll_Creator.Creator_ID = " + creatorID;

        ArrayList<Poll> pollArray = new ArrayList<Poll>();
        Poll poll;

        try {
            ResultSet results = DatabaseQuery(sql);

            while (results.next()) {
                poll = new Poll();

                poll.setId(results.getInt("Poll_ID"));
                poll.setName(results.getString("Poll_Name"));

                long time = results.getLong("Creation_Date");
                java.util.Date date = new java.util.Date(time);
                poll.setCreationDate(date);
                
                if (results.getString("Public_Result").equals("Yes")) {
                    poll.setPublicResult();
                } else {
                    poll.setPrivateResult();
                }

                if (results.getString("Anonymous").equals("Yes")) {
                    poll.setAnonymous(true);
                } else {
                    poll.setAnonymous(false);
                }

                pollArray.add(poll);
            }

            return pollArray;

        } catch (Exception ex) {
            m_logger.info("getPolls() failed\n");
            m_logger.info(ex.toString());
        }
        return null;
    }

    public boolean assignPM(int pollID, int masterID) {

        m_logger.info("\nassignPM\n\n");

        String sql = "INSERT INTO Poll_Master VALUES(" + pollID + ", " + masterID + ")";
        m_logger.info(sql);

        try {
            if (DatabaseInsert(sql)) {
                return true;
            }
            return false;
        } catch (Exception ex) {
            m_logger.info("assignPM() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
    }

    /**
     * Function that adds a new Multiple Choice Question to the database
     * 
     * @param questionText text of the question to be asked
     * @param style Vertical/Horizontal/Pie
     * @param template Is it a template question Yes/No
     * @param ranking is it a ranking question Yes/No
     * @param demographic is it a demographic question Yes/No
     * @param comparison is it a comparison question Yes/No
     * @param pollID id of the parent poll
     * @return 
     */
    public boolean addMCQuestion(String questionText, String style, String template, String ranking, String demographic, String comparison, int pollID) {//TODO @Tom Make good work again
        int nextQuestionID = getNextID("Question");
        int nextMCQuestionID = getNextID("MC_Question");
        return addMCQuestionReal(nextQuestionID, nextMCQuestionID, questionText, style, template, ranking, demographic, comparison, pollID);
    }
    
    
    public boolean addMCQuestionReal(int QuestionID, int MCQuestionID, String questionText, String style, String template, String ranking, String demographic, String comparison, int pollID) {



        long time = new java.util.Date().getTime();

        String sql1 = "INSERT INTO Question VALUES(" + QuestionID + ", '" + questionText + "', "+time+", 'MC', 'No', 0, 'No', " + pollID + ")";
        String sql2 = "INSERT INTO MC_Question VALUES(" + MCQuestionID + ", '" + style + "', '" + template + "', '" + ranking + "', '" + demographic + "', '" + comparison + "', " + QuestionID + ")";

        try {
            if (!DatabaseInsert(sql1)) {
                m_logger.info("Insert into Question table failed\n");
                return false;
            }
            if (!DatabaseInsert(sql2)) {
                m_logger.info("Insert into MC_Question table failed\n");
                return false;
            }
        } catch (Exception ex) {
            m_logger.info("addMCQuestion() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
        return true;

    }

    /**
     * Function that adds a new Short Response Question
     * 
     * @param questionText the text of the question that you are asking
     * @param questionType Numeric or Alphanumeric
     * @param pollID the ID of the parent poll
     * @return 
     */
    public boolean addSRQuestion(String questionText, String questionType, int pollID) {
        int nextQuestionID = getNextID("Question");
        int nextSRQuestionID = getNextID("SR_Question");
        
        return addSRQuestionReal(nextQuestionID, nextSRQuestionID, questionText, questionType, pollID);
    }
        
    public boolean addSRQuestionReal(int questionID, int SRQuestionID, String questionText, String questionType, int pollID) {



        long time = new java.util.Date().getTime();

        String sql1 = "INSERT INTO Question VALUES(" + questionID + ", '" + questionText + "', "+time+", 'No', 0, 'No', " + pollID + ")";
        String sql2 = "INSERT INTO SR_Question VALUES(" + SRQuestionID + ", '" + questionType + "', " + questionID + ")";

        try {
            if (!DatabaseInsert(sql1)) {
                m_logger.info("Insert into Question table failed\n");
                return false;
            }
            if (!DatabaseInsert(sql2)) {
                m_logger.info("Insert into SR_Question table failed\n");
                return false;
            }
        } catch (Exception ex) {
            m_logger.info("addSRQuestion() failed\n");
            m_logger.info(ex.toString());
            return false;
        }
        return true;
    }

    public boolean addLocationToPoll(int pollID, double latitude, double longitude, String name) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
    public final boolean deleteMCAnswer(int answerID) {
        String sql = "UPDATE MC_Answer SET Deleted = 'Yes' WHERE Answer_ID = " + answerID;
        try {
            if (DatabaseInsert(sql)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception Ex) {
            m_logger.info("deleteMCAnswer("+answerID+") failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
    
    public boolean deleteSRKeyword(int keywordID) {
        String sql = "UPDATE SR_Keyword SET Deleted = 'Yes' WHERE Answer_ID = " + keywordID;
        try {
            if (DatabaseInsert(sql)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception Ex) {
            m_logger.info("deleteSRKeyword("+keywordID+") failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
    
    public boolean deleteQuestion(int questionID) {
        String sql = "SELECT Question_Type FROM Question WHERE Question_ID = "+questionID;
        try {
            ResultSet results = DatabaseQuery(sql);
            if (results.next()) {
//                if (results.getString("Question_Type").equals("MC")) {
//                    sql = "UPDATE MC_Answer SET Deleted = 'Yes' WHERE Question_ID = "+questionID;
//                    if (!DatabaseInsert(sql)) {
//                        return false;
//                    }
//                    sql = "UPDATE MC_Question SET Deleted = 'Yes' WHERE Question_ID = "+questionID;
//                    if (!DatabaseInsert(sql)) {
//                        return false;
//                    }
//                } else {
//                    sql = "UPDATE SR_Keyword SET Deleted = 'Yes' WHERE Question_ID = "+questionID;
//                    if (!DatabaseInsert(sql)) {
//                        return false;
//                    }
//                    sql = "UPDATE SR_Question SET Deleted = 'Yes' WHERE Question_ID = "+questionID;
//                    if (!DatabaseInsert(sql)) {
//                        return false;
//                    }
//                }
                sql = "UPDATE Question SET Deleted = 'Yes' WHERE Question_ID = "+questionID;
                DatabaseInsert(sql);
            }
            return true;
        } catch (Exception Ex) {
            m_logger.info("deleteQuestion("+questionID+") failed");
            m_logger.info(Ex.toString());
            return false;
        }

    }
    
    public boolean editMCQuestion(int questionID, String questionText, String style, String template, String ranking, String demographic, String comparison, int pollID) {
        int qID = getNextID("Question");
        int MCID = getNextID("MC_Question");
        
        try {
            String sql = "SELECT * FROM MC_Question WHERE Question_ID = "+questionID;
            ResultSet results = DatabaseQuery(sql);
            int oldMCID = results.getInt("MC_Question_ID");
            
            sql = "UPDATE Question SET Question_ID = "+qID+", overwritten = 'Yes' WHERE Question_ID = "+questionID;
            if (!DatabaseInsert(sql)) {
                return false;
            }
            sql = "UPDATE MC_Question SET MC_Question_ID = "+MCID+", overwritten = 'Yes' WHERE MC_Question_ID = "+MCID;
            if(!DatabaseInsert(sql)){
                return false;
            }
            return addMCQuestionReal(questionID, oldMCID, questionText, style, template, ranking, demographic, comparison, pollID);
        } catch (Exception Ex) {
            m_logger.info("editMCQuestion("+questionID+") failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
    
    public boolean editSRQuestion(int questionID, int SRQuestionID, String questionText, String questiontype, int pollID) {
        int qID = getNextID("Question");
        int SRID = getNextID("SR_Question");
        
        try {
            String sql = "SELECT * FROM SR_Question WHERE Question_ID = "+questionID;
            ResultSet results = DatabaseQuery(sql);
            int oldSRID = results.getInt("SR_Question_ID");
            
            sql = "UPDATE Question SET Question_ID = "+qID+", overwritten = 'Yes' WHERE Question_ID = "+questionID;
            if (!DatabaseInsert(sql)) {
                return false;
            }
            sql = "UPDATE MC_Question SET SR_Question_ID = "+SRID+", overwritten = 'Yes' WHERE SR_Question_ID = "+SRID;
            if(!DatabaseInsert(sql)){
                return false;
            }
            return addSRQuestionReal(questionID, oldSRID, questionText, questiontype, pollID);
        } catch (Exception Ex) {
            m_logger.info("editSRQuestion("+questionID+") failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
    
    public boolean addMCAnswer(String text, boolean correct, int weighting, int questionID) {
        int ID = getNextID("MC_ANSWER");
        String correctString;
        if (correct) {
            correctString = "Yes";
        } else {
            correctString = "No";
        }
        String sql = "INSERT INTO MC_Answer Values("+ID+","+text+","+correctString+","+weighting+",'No',"+questionID;
        try {
            if (DatabaseInsert(sql)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception Ex) {
            m_logger.info("addMCAnswer failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
    
    public boolean addSRKeyword(String text, int questionID) {
        int ID = getNextID("SR_KEYWORD");
        String sql = "INSERT INTO MC_Answer Values("+ID+","+text+",'No',"+questionID;
        try {
            if (DatabaseInsert(sql)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception Ex) {
            m_logger.info("addSRKeyword failed");
            m_logger.info(Ex.toString());
            return false;
        }
    }
}
